今天要來介紹一下SharedPreferences,這是一個可以以Key-Value的方式來儲存資料,可以把它當作是一個簡單的小資料庫
public class SharedPf {
private String test;
private SharedPreferences sharedPf;
private Context context;
public SharedPf(Context context){
this.context = context;
sharedPf=this.context.getSharedPreferences("USER",Context.MODE_PRIVATE);//設定MODE
}
public String getTest() {
//拿取資料
return sharedPf.getString("TEST","");
}
public void setTest(String test) {
//設定資料
sharedPf.edit().putString("TEST",test).commit();
}
}
public class MainActivity extends AppCompatActivity {
private SharedPf sharedPf;
private Button button;
private Button button3;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button3 = findViewById(R.id.button3);
editText = findViewById(R.id.editTextText);
sharedPf = new SharedPf(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sharedPf.setTest(editText.getText().toString());
Toast.makeText(MainActivity.this,"已儲存資料" + editText.getText().toString() + "!",Toast.LENGTH_SHORT).show();
editText.setText("");
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editText.setText(sharedPf.getTest());
Toast.makeText(MainActivity.this,"已拿取資料!",Toast.LENGTH_SHORT).show();
}
});
}
}
結果如下